package com.buho29.rcmanager.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;

public class BitmapUtils {

    private final static Paint PAINT = new Paint(Paint.DITHER_FLAG);
	
	public static  int resolveSampleSize(Options options , int width) {
		int w = options.outWidth;
		int h = options.outHeight;
		
		w = Math.max(w, h);
		
		int scaleFactor = 1;
		while (w / scaleFactor > width) {
		    scaleFactor *= 2;
		}
		return scaleFactor;
	}
    
    public static Bitmap rotateBitmap(Bitmap source) {
		Matrix m = new Matrix();
		m.setRotate(90.0f);
		Bitmap result = Bitmap.createBitmap(source, 0, 0, 
				source.getWidth(), source.getHeight(), m, true);
		source.recycle();
        return result;
	}

	public static Bitmap scaleBitmap(Bitmap source, int width, int height) {
        final int w = source.getWidth();
        final int h = source.getHeight();

        final float scale = Math.min( (float)width/(float)w, (float)height/(float)h);

        Bitmap result = Bitmap.createScaledBitmap(source, (int)(w * scale), (int)(h * scale), true);
        source.recycle();
        return result;

    }
    
    public static Bitmap croppedBitmap(Bitmap source, int width, int height) {
        int w = source.getWidth();
        int h = source.getHeight();
        
        int x = 0;
        int y = 0;

        final float scaleW = (float)width/(float)w ;
        final float scaleH = (float)height/(float)h;
        
        if(scaleW>scaleH){
        	w = (int) (w / scaleW+0.5f);
        	h = (int) (h / scaleW+0.5f);
        	x = (width-w)/2;
        }else{
        	w = (int) (w / scaleH+0.5f);
        	h = (int) (h / scaleH+0.5f);
        	y = (height-h)/2;
        }

        Bitmap result = Bitmap.createBitmap(width,height,Config.ARGB_8888);
        Canvas c = new Canvas(result);
        
        c.drawBitmap(source, 
        	new Rect(x,y,w,h), 
        	new Rect(0,0,width,height),
        PAINT);
        
        source.recycle();
        return result;
    }
}
